package br.com.ecomanda.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.ecomanda.controller.EComandaController;
import br.com.ecomanda.model.Item;
import br.com.ecomanda.util.JSFUtil;

public class ItemConverter implements Converter {

	private EComandaController parent;

	public ItemConverter() {
		this.parent = (EComandaController) JSFUtil.getFromSession("parent");
	}

	public ItemConverter(EComandaController parent) {
		this.parent = parent;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		try {
			int itemId = Integer.parseInt(value);
			Item item = parent.getPedidoController().getItem(itemId);
			return item;
		} catch (NumberFormatException e) {
			return null;
		} 
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if(value == null || value.getClass() != Item.class)
			return null;
			
		Item item = (Item) value;
		
		if(item.getIdItem() == 0)
			return null;
		
		return item.getIdItem() + "";
	}

}
